//
//  NIBaseService.m
//  WeCloudSDK
//
//  Created by Navinfo on 2018/4/2.
//  Copyright © 2018年 navinfo. All rights reserved.
//

#import "NIBaseService.h"
#import "AFHTTPSessionManager.h"
#import "WeCloudManager.h"
#import "YYModel.h"
#import "AppContext.h"
#import "NIResultObject.h"

static BOOL isMock = NO;

@implementation NIBaseService{
}

- (void)sendRequest:(NIBaseRequestObject *)requestObject
            success:(void (^)(id _Nullable))success
            failure:(void (^)(NIResultObject * _Nonnull))failure{
    _requestObject = requestObject;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer new];
    manager.responseSerializer.acceptableContentTypes = [NSSet
                                                         setWithObjects:@"application/json",@"text/json",
                                                         @"text/plain", @"text/html",
                                                         nil];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    NSDictionary *headerDic = [self buildRequestHeaderParams];
    NSArray *allKeys = [headerDic allKeys];
    for (NSString *key in allKeys) {
        [manager.requestSerializer setValue:[headerDic objectForKey:key] forHTTPHeaderField:key];

    }
    
    NSDictionary *paramsDic = [self buildRequestParams];
    NSString *paramsString = [self convertToJsonData:paramsDic];
    NSLog(@"日志——请求地址:%@?%@",[NSString stringWithFormat:@"%@%@",_requestObject.urlString,_requestObject.interfaceName],paramsString);
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval=30;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager POST:[NSString stringWithFormat:@"%@%@",_requestObject.urlString,_requestObject.interfaceName] parameters:[self buildRequestBodyParams] progress:^(NSProgress * _Nonnull uploadProgress) {
        //一般请求过程中无需处理
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"日志——返回数据源数据:%@",responseObject);
        NSString *responseData = responseObject;
        if ([responseObject isKindOfClass:[NSData class]]) {
            responseData =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        }
        NSLog(@"日志——返回数据:%@",responseData);
        BOOL businessSuccess = NO;
        NIResultObject *result = [NIResultObject yy_modelWithJSON:responseData];
        if(result){
            //0:成功
            if (result.errorCode == 0) {
                Class targetClass = [NSClassFromString(_requestObject.targetModelClassName) class];
                id object = [targetClass yy_modelWithJSON:responseData];
                if (object) {
                    businessSuccess = YES;
                    success(object);
                    return;
                }
                result = [self buildErrorResult];
            }
        }else{
            result = [self buildJsonErrorResult];
        }
        if (!businessSuccess) {
            failure(result);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求:%@",error.description);
        NIResultObject *result;
        if (error) {
            result = [self getErrorResultWithCode:error.code];
        }
        failure(result);
    }];
}

- (NIResultObject *)buildErrorResult{
    NIResultObject *result = [[NIResultObject alloc] init];
    result.errorCode = -4002;
    result.errorMessage = @"数据解析错误";
    return result;
}

- (NIResultObject *)buildJsonErrorResult{
    NIResultObject *result = [[NIResultObject alloc] init];
    result.errorCode = -4001;
    result.errorMessage = @"返回数据格式错误";
    return result;
}

- (NIResultObject *)getErrorResultWithCode:(NSInteger) code{
    NIResultObject *result = [[NIResultObject alloc] init];
    switch (code) {
        case -1009:
            result.errorCode = -3001;
            result.errorMessage = @"未检查到网络连接";
            break;
        case -1001:
            result.errorCode = -3002;
            result.errorMessage = @"网络连接超时";
            break;
            
        default:
            result.errorCode = -3003;
            result.errorMessage = @"网络连接失败";
            break;
    }
    return result;
}

-(NSDictionary *)buildRequestParams
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithCapacity:0];
    [dic setObject:[self buildRequestHeaderParams] forKey:@"header"];
    [dic setObject:[self buildRequestBodyParams] forKey:@"body"];
    return dic;
}

- (NSDictionary *)buildRequestBodyParams{
    //最终的请求内容
    return [_requestObject getDicFromObject];
    
}


- (NSDictionary *)buildRequestHeaderParams{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmssSSS"];
    NSString *timeStr= [dateFormatter stringFromDate:[NSDate date]];
    WeCloudManager *shareManager = [WeCloudManager shareInstance];
    NSString *token;
    if (shareManager.token) {
        token = shareManager.token;
    }
    else
    {
        token = @"";
    }
//    return @{@"rs":TSP_RS,@"ts":timeStr,@"v":TSP_V,@"fn":_requestObject.interfaceName,@"fv":TSP_FV,@"tk":@"2862a53e08474738a213de7a955ae922",@"osType":@"iOS",@"osVer":[[UIDevice currentDevice] systemVersion],@"mobileId":shareManager.mobileID,@"cVer":APP_VERSION};
    
    
    return @{@"time":timeStr,@"token":token,@"device_type":@"iOS",@"app_version":APP_VERSION,@"device_id":[AppContext getInstance].deviceId};
    
}


-(NSString *)convertToJsonData:(NSDictionary *)dict{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}



- (void)sendRequest:(NIBaseRequestObject *)requestObject
         imageArray:(NSArray<UIImage *>*)imageArray
         imageNames:(NSArray*)imageNames
            success:(void (^)(id _Nullable))success
            failure:(void (^)(NIResultObject * _Nonnull))failure{
    _requestObject = requestObject;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer new];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:
                                                          @"application/json",
                                                          @"text/html"       ,
                                                          @"image/jpeg"      ,
                                                          @"image/png"       ,
                                                          @"image/jpg"       ,
                                                          @"application/octet-stream",
                                                          @"text/json"      ,
                                                          nil] ;

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    NSDictionary *headerDic = [self buildRequestHeaderParams];
    NSArray *allKeys = [headerDic allKeys];
    for (NSString *key in allKeys) {
        [manager.requestSerializer setValue:[headerDic objectForKey:key] forHTTPHeaderField:key];
        
    }
    
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval=30;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager POST:[NSString stringWithFormat:@"%@%@",_requestObject.urlString,_requestObject.interfaceName] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         NSDictionary *dic = [self buildRequestBodyParams];
         NSLog(@"日志——数据:%@",[self buildRequestBodyParams]);
         NSArray *allKeys = [dic allKeys];
         for (NSString *key in allKeys) {
             
             NSData *data = [[dic objectForKey:key] dataUsingEncoding:NSUTF8StringEncoding] ;
             [formData appendPartWithFormData:data name:key] ;
         }
         
         for (int i = 0; i < imageArray.count; i++) {
             //在网络开发中，上传文件时，文件是不允许被覆盖，文件重名
             //要解决此问题，可以在上传时使用当前的系统事件作为文件名
             NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
             
             //设置时间格式
             formatter.dateFormat = @"yyyyMMddHHmmssSSS" ;
             NSString *str = [formatter stringFromDate:[NSDate date]] ;
             NSString *fileName = [NSString stringWithFormat:@"%@.jpg",str] ;
             UIImage *image = imageArray[i];
             NSData *data = UIImagePNGRepresentation(image);
             [formData appendPartWithFileData:data name:imageNames[i] fileName:fileName mimeType:@"image/jpg"];
         }
     }
     
     //上传过程中调用
          progress:^(NSProgress * _Nonnull uploadProgress)
     {
         
     }
     
     //上传成功调用
           success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSLog(@"上传成功！") ;
         //        NSLog(@"日志——返回数据源数据:%@",responseObject);
         NSString *responseData = responseObject;
         if ([responseObject isKindOfClass:[NSData class]]) {
             responseData =  [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
         }
         NSLog(@"日志——返回数据:%@",responseData);
         BOOL businessSuccess = NO;
         NIResultObject *result = [NIResultObject yy_modelWithJSON:responseData];
         if(result){
             //0:成功
             if (result.errorCode == 0) {
                 Class targetClass = [NSClassFromString(_requestObject.targetModelClassName) class];
                 id object = [targetClass yy_modelWithJSON:responseData];
                 if (object) {
                     businessSuccess = YES;
                     success(object);
                     return;
                 }
                 result = [self buildErrorResult];
             }
         }else{
             result = [self buildJsonErrorResult];
         }
         if (!businessSuccess) {
             failure(result);
         }
     }
           failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         NSLog(@"上传失败") ;
         NSLog(@"请求:%@",error.description);
         NIResultObject *result;
         if (error) {
             result = [self getErrorResultWithCode:error.code];
         }
         failure(result);
     }] ;

}
/**< Demo 使用 */
+ (void)setMock:(BOOL)setMock{
    isMock = setMock;
}
+ (BOOL)isMock{
    return isMock;
}
@end
